import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {HttpClient} from "@angular/common/http";


@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styleUrls: ['./edit-user.component.css']
})
export class EditUserComponent implements OnInit {
  registerForm: FormGroup;

  genderOpts = [{label: 'Male', value: 1}, {label: 'Female', value: 2}, {label: 'Other', value: 3}];
  value3: String | undefined;
  value4: String | undefined;

  constructor(
    private readonly fb: FormBuilder,
    private readonly http: HttpClient
  ) {
    this.registerForm = this.fb.group({
      username: ['', Validators.required],
      name: ['', Validators.required],
      gender: ['', Validators.required],
      phoneNum: ['',Validators.required],
      birthday: ['', Validators.required],
      homeAddress: ['',Validators.required],
      password: ['', [Validators.required,Validators.minLength(6),Validators.maxLength(15)]],
      confirmPassword:['',Validators.required],
      isAdmin: [false],
      acceptTerms:[false,Validators.required]

    },{
      validators:MustMatch("password","confirmPassword")
    });

  }

  ngOnInit(): void {
  }
  checkDigitRe = new RegExp('.*[0-9].*');//判断带有数字
  checkSpecialCharRE = new RegExp(/^(?=.*?[ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"])/);//判断特殊符号
  commonPasswordList = [
    '!@#$%^&*','!@#$%^&amp;*','!£$%^&*','12341234','12345678','123456789','1qaz2wsx','87654321','987654321','aa123456',
    'aa123456w','admin123','asdfghjk','baseball','computer','corvette','football','iloveyou','jennifer','liverpool',
    'maverick','mercedes','pass1234','passw0rd','password1','password12','password123','princess','qwerty123','starwars','sunshine',
    'trustno1','whatever','zaq1zaq1','blahblah','password','qwertyui'
  ]
  get dateGit(){
    return !this.checkDigitRe.test(this.f.password.value);
  }
  get dataSprcial(){
    return !this.checkSpecialCharRE.test(this.f.password.value);
  }
  get dataComm(){
    return this.commonPasswordList.indexOf(this.f.password.value)>-1;
  }

  get f() {
    return this.registerForm.controls;
  }


  onSubmit() {
    // alert(JSON.stringify(this.registerForm.value))
    this.http.post('/user', this.registerForm.value)
      .subscribe((result: any) => alert(result));
  }

  onReset() {
    this.registerForm.reset();
  }
}

export function MustMatch(controlName: string, matchingControlName: string) {
  return (formGroup: FormGroup) => {
    const control = formGroup.controls[controlName];
    const matchingControl = formGroup.controls[matchingControlName];

    if (matchingControl.errors && !matchingControl.errors.mustMatch) {
      // 如果另一个验证器已经在matchingControl上发现错误，则返回
      return;
    }

    // 如果验证失败，则在 matchingControl 上设置错误
    if (control.value !== matchingControl.value) {
      matchingControl.setErrors({mustMatch: true});
    } else {
      matchingControl.setErrors(null);
    }
  }
}
